IF OBJECT_ID('ssf.log_begin') IS NOT NULL
	DROP PROCEDURE ssf.log_begin
GO

CREATE PROCEDURE ssf.log_begin
	@source_object NVARCHAR(512) = NULL
	, @task NVARCHAR(512) = NULL
	, @task_description NVARCHAR(2048) = NULL
	, @target_object NVARCHAR(512) = NULL
	, @log_sql NVARCHAR(MAX) = NULL
	, @log_id BIGINT = NULL OUTPUT
AS
/*

*/

SET NOCOUNT ON

-- ============
/*<code_comment><![CDATA[declare local variables]]></code_comment>*/
DECLARE 	@sql_error INT
			, @row_count INT
-- ============

-- ============
/*<code_comment><![CDATA[insert new log record]]></code_comment>*/
SET @log_id = NULL

INSERT ssf.log_info (
	begin_spid
	, begin_login
	, begin_log_time
	, source_object
	, task
	, target_object
	, task_description
	, log_sql
)
VALUES (
	@@SPID
	, SUSER_SNAME()
	, SYSDATETIME()
	, NULLIF(@source_object, '')
	, NULLIF(@task, '')
	, NULLIF(@target_object, '')
	, NULLIF(@task_description, '')
	, NULLIF(@log_sql, '')
)

SELECT @sql_error = @@ERROR
	, @row_count = @@ROWCOUNT
	, @log_id = SCOPE_IDENTITY()

IF @sql_error <> 0
OR @row_count <> 1
OR @log_id IS NULL
BEGIN
	RAISERROR('The INSERT into the table <ssf.log_info> failed.', 16, 1)
	RETURN @sql_error
END
-- ============

RETURN @@ERROR
GO
